package cn.xiaopengstack.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author jiangyangang
 */
@Data
@ConfigurationProperties(prefix = "spring.ai")
public class SpringAiProperties {

    private String ragEmbed;

    private Ollama ollama;

    private OpenAi openAi;

    private Deepseek deepseek;

    private Postgres postgres;

    @Data
    public static class Postgres{
        private String tableName;
    }

    @Data
    public static class OpenAi{
        private String baseUrl;

        private List<String> models;

        private String apiKey;

        private Embedding embedding;

    }

    @Data
    public static class Ollama{
        private String baseUrl;

        private List<String> models;

        private String apiKey;

        private Embedding embedding;

    }

    @Data
    public static class Deepseek{
        private String baseUrl;

        private List<String> models;

        private String apiKey;

        private Embedding embedding;
    }

    @Data
    public static class Embedding{
        private String model;

        private Integer dimensions;
    }

    /**
     * 使用反射获取所有models字段的值
     * @return
     */
    public List<String> getAllDisplayAiModels(){
        Class<? extends SpringAiProperties> aClass = this.getClass();
        // 获取所有字段的实例
        Field[] declaredFields = aClass.getDeclaredFields();
        List<String> allModels = new ArrayList<>();

        Stream.of(declaredFields).forEach(field -> {
            try {
                // 获取字段的实例
                Object fieldObj = field.get(this);
                Class<?> fieldClazz = fieldObj.getClass();
                // 获取models字段
                Field fieldModels = fieldClazz.getDeclaredField("models");
                fieldModels.setAccessible(true);

                // 组装
                Object list = fieldModels.get(fieldObj);
                if (list instanceof List) {
                    allModels.addAll((List<String>) list);
                }

            } catch (Exception e) {
                System.out.println("不是models字段，忽略");
            }
        });

        return ModelNameVal.init(allModels).stream().map(ModelNameVal::getDisplayName).toList();
    }
}
